package org.siscoh.model.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.siscoh.model.bean.AbstractBean;
import org.siscoh.model.bean.CategoriaBean;
import org.siscoh.model.bean.EspecificacaoBean;
import org.siscoh.model.bean.EspecificacaoItemBean;
import org.siscoh.model.bean.ItemBean;

/**
 */
public class ItemDao extends AbstractDao {

    private boolean lazy;
    
    public ItemDao()
    {
        lazy = true;
    }
    
    public ItemDao(boolean isLazy)
    {
        this.lazy = isLazy;
    }
    
    @Override
    public void update(AbstractBean bean) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void insert(AbstractBean bean) {
        ItemBean item = (ItemBean) bean;
        
        long id = Conexao.getInstance().insert("item",
                new String[]{"categoria_id",                "nome",         "quantidade"},
                new String[]{item.getCategoria().getId()+"",item.getNome(), item.getQuantidade()+""});
        
        if(id == -1)
        {
            System.err.println("Erro ao inserir item no banco!");
            return;
        }
        
        item.setId(id);
        
        EspecificacaoItemDao espItDao = new EspecificacaoItemDao();
        EspecificacaoItemBean espItem = new EspecificacaoItemBean();
        
        HashMap<Long, String> map = item.getEspecificacoes();
        Set<Long> chaves = map.keySet();
        
        Iterator it = chaves.iterator();
        
        while(it.hasNext())
        {
            Long espId = (Long) it.next();
            String value = map.get(espId);
            
            EspecificacaoBean espBean = (EspecificacaoBean) new EspecificacaoDao().selectById(espId);
            
            espItem.setEspecificacao(espBean);
            espItem.setValor(value);
            espItem.setItem(id);
            
            espItDao.insert(espItem);
        }
    }
    
    public ItemBean[] searchItens(long categoria, String input)
    {
        ArrayList<ItemBean> al = searchItensAL(categoria, input);
        
        int size = al.size();
        
        ItemBean[] itens = new ItemBean[size];
        
        for(int i = 0; i < size; i++)
        {
            itens[i] = al.get(i);
        }
        
        return itens;
    }
    
    public ArrayList<ItemBean> searchItensAL(long categoria, String input)
    {
        String query = "SELECT * FROM item WHERE ";
        
        String inputs[] = input.split(" ");
        
        
        if(inputs.length > 1)
        {
            int i;
            for(i = 0; i < inputs.length-1; i++)
            {
                query += "nome like '%"+inputs[i]+"%' OR ";
            }
            query += "nome like '%"+inputs[i]+"%' ";
        }
        else
        {
            query += "nome like '%"+inputs[0]+"%' ";
        }        
        
        if(categoria != -1)
        {
            query += " AND categoria_id = '"+categoria+"'";
        }
        
        query += " ORDER BY nome";
        
        ResultSet rs = Conexao.getInstance().customSelect(query);
        
        System.err.println("------------------------------------------------");
        System.err.println("Query = "+query);
        System.err.println("------------------------------------------------");
        
        return parseRsToObjects(rs);
    }

    @Override
    public void delete(AbstractBean bean) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ArrayList<AbstractBean> fetchAllArrayList() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public AbstractBean[] fetchAll() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public AbstractBean selectById(long id) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    protected AbstractBean parseRsToObject(ResultSet rs) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    protected ArrayList<ItemBean> parseRsToObjects(ResultSet rs) {
        ArrayList<ItemBean> itemList = new ArrayList<ItemBean>();
        
        EspecificacaoItemDao espItemDao = new EspecificacaoItemDao();
        
        try {
            long catId = -1, newCatId;
            CategoriaBean oldCb = null;
            while(rs.next())
            {
                ItemBean ib = new ItemBean();
                
                ib.setId(rs.getLong("id"));
                ib.setNome(rs.getString("nome"));
                ib.setQuantidade(rs.getInt("quantidade"));
                
                newCatId = rs.getLong("categoria_id");
                
                CategoriaBean cb;
                
                if(newCatId == catId)
                {
                    cb = oldCb;
                }
                else
                {
                    catId = newCatId;
                    cb = (CategoriaBean) new CategoriaDao().selectById(catId);
                    oldCb = cb;
                }
                
                if(!lazy)
                {
                    ib.setEspecificacoesList(espItemDao.fetchByItem(ib.getId()));
                }
                
                ib.setCategoria(cb);
                itemList.add(ib);
            }
        } catch (SQLException ex) {
            ex.printStackTrace(System.err);
        }
        
        return itemList;
    }
}
